define(["jquery","echarts","migrate_jqprint","jqprint","bbcare","as/app/growth/growthDetail.servers","as/app/growth/growthDetail.ui"],function($,echarts,migrate,$print,$bb,$servers,$ui){
	var event = {};

    /**
     * Fenton图
     */
    var fentonTrends = function(dom,series,gender){
        var myChart = echarts.init(document.getElementById(dom));
        var gender = gender == "F" ? "女" : gender == "M" ? "男" : gender;
        // 指定图表的配置项和数据
        var option = {
            title: {
                text: 'Fenton早产儿发育图-'+gender,
                left:"89%",
                top:"1.5%",
                textAlign:'right',
                textBaseline:"top",
                textStyle: {
                    color: '#fff',
                    fontSize: '12',
                    fontWeight:"normal"
                }
            },
            tooltip: {
                formatter:function(params, ticket, callback){
                    var val="";
                    if(params.data instanceof Array){
                        val+=params.seriesName+": "+parseFloat(params.data[1]).toFixed(3);
                    }else{
                        if(params.seriesName == "身长" || params.seriesName == "体重" || params.seriesName == "头围"){
                            if(params.componentType=="markPoint"){
                                if(params.seriesName == "体重"){
                                    val+="胎龄:"+$servers.toPregnancyDay(params.data.coord[0])+"<br/>"+params.seriesName+":"+parseFloat(params.data.coord[1]).toFixed(2);
                                }else{
                                    val+="胎龄:"+$servers.toPregnancyDay(params.data.coord[0])+"<br/>"+params.seriesName+":"+parseFloat(params.data.coord[1]).toFixed(1);
                                }
                            }
                        }else{
                            val+=params.seriesName+": "+parseFloat(params.data.value[1]).toFixed(3);
                        }
                    }
                    return val;
                }
            },
            grid: {
                show:true,
                left: '0',
                right: '0',
                bottom: '3%',
                top:'4%',
                containLabel: true
            },
            xAxis:  {
                type:"value",
                name: '胎龄（周）',
                nameLocation: 'middle',
                nameGap:"27",
                nameTextStyle: {color: "#fff"},
                max:50,
                min:22,
                interval:1,
                splitLine:{
                    lineStyle:{
                        color:["#333","#ccc","#333","#ccc","#ccc","#ccc","#333","#ccc","#ccc","#ccc", "#333","#ccc","#ccc",
                            "#ccc","#333","#ccc","#ccc","#ccc","#333","#ccc","#ccc","#ccc","#333","#ccc","#ccc","#ccc"],
                        width:1
                    }
                },
                axisTick: {
                    show: true,
                    inside: true
                },
                axisLabel: {
                    textStyle: {
                        color: function(value){
                            return  value % 2 != 0 ?"transparent":"#fff";
                        }
                    }
                }
            },
            yAxis: [
                {
                    name: '体重（kg)                                                             厘米',
                    nameLocation: 'middle',
                    nameGap:"30",
                    nameTextStyle: {color: "#fff"},
                    max: 9,
                    min:0,
                    interval:0.1,
                    type: 'value',
                    splitArea : {
                        show :true,//保留网格区域
                        areaStyle:{
                            color:"#fff"
                        }
                    },
                    axisTick: {
                        inside: true
                    },
                    axisLabel: {
                        textStyle: {
                            color: function(value,index){
                                return  value>4?"transparent":value*10%5!=0 ? "transparent":"#fff";
                            }
                        }
                    }
                },
                {
                    name:'体重（kg)                                                                                                         厘米',
                    nameLocation: 'middle',
                    nameGap:"27",
                    nameTextStyle: {color: "#fff"},
                    type: 'value',
                    max: 60,
                    min:-30,
                    interval:1,
                    axisTick: {
                        inside: true
                    },
                    axisLabel: {
                        textStyle: {
                            color: function(value,index){
                                return  value<40?"transparent":value%5!=0 ? "transparent":"#FFF";
                            }
                        }
                    }
                },
                {
                    position:'left',
                    type: 'value',
                    max: 60,
                    min:-30,
                    interval:1,
                    axisTick: {
                        inside: true
                    },
                    axisLabel: {
                        textStyle: {
                            color: function(value,index){
                                return  value<15?"transparent":value%5!=0 ? "transparent":"#FFF";
                            }
                        }
                    }
                },
                {
                    type: 'value',
                    position:'right',
                    max: 9,
                    min:0,
                    interval:0.1,
                    splitLine:{
                        lineStyle:{
                            color:["#333","#ccc","#ccc","#ccc","#ccc"],
                            width:1
                        }
                    },
                    axisTick: {
                        inside: true
                    },
                    axisLabel: {
                        textStyle: {
                            color: function(value,index){
                                return value>6.5?"transparent":value*10%5!=0 ? "transparent":"#FFF";
                            }
                        }
                    }
                }
            ],
            animation:false,
            series:series
        };
        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
        $("#" + dom + "Print").html('<img src="' + myChart.getDataURL({type: "png",backgroundColor: '#aaa'}) + '" style="width:100%;height:100%;"/>');
    }

    /**
     * 生长发育图
     */
	var trend = function(dom,res,interval,i,sexColor) {
        var myChart = echarts.init(document.getElementById(dom));
        //var colors = ['#00612d','#ffb13d','#e41836','#252122'];//0--SD0,1--SD1,SD1neg,2--SD2,SD2neg,3--SD3,SD3neg
        var colors = ['#12aa59','#ffb13d','#e76b7d','#6d555b'];//0--SD0,1--SD1,SD1neg,2--SD2,SD2neg,3--SD3,SD3neg
        var option = {
            textStyle: {
                fontSize: "15px",
                color:"#fff"
            },
            tooltip: {
                trigger: 'item',
                axis:"x",
                formatter:function(params, ticket, callback){
                    // 获取y轴单位
                    var yUnit = $servers.getUnit(res.yName);
                    if(res.xType=="height"){
                        var xUnit = $servers.getUnit(res.xName);
                        var val=' ';
                        if(params.seriesName=="baby"){
                            if(params.data instanceof Array){
                                val += res.xName.substring(0,2) + ": " + parseFloat(params.data[0]).toFixed(3) + xUnit + "<br/>" + res.yName.substring(0,2) + ": " + parseFloat(params.data[1]).toFixed(3) + yUnit;
                            }else{
                                if(params.componentType=="markPoint"){
                                    val += res.xName.substring(0,2) + ": " + parseFloat(params.data.coord[0]).toFixed(3) + xUnit + "<br/>" + res.yName.substring(0,2) + ": " + parseFloat(params.data.coord[1]).toFixed(3) + yUnit;
                                }else{
                                    val += res.xName.substring(0,2) + ": " + parseFloat(params.data.value[0]).toFixed(3) + xUnit + "<br/>" + res.yName.substring(0,2) + ": " + parseFloat(params.data.value[1]).toFixed(3) + yUnit;
                                }
                            }
                        }else{
                            val += parseFloat(params.data[0]).toFixed(3) + xUnit + " / " + params.data[1] + yUnit;
                        }
                    }
                    if(res.xType=="age"){
                        val=" ";
                        if(params.seriesName=="baby"){
                            var babyAge;
                            if(params.data instanceof Array){
                                babyAge = $servers.babyAgeDeal(res,parseFloat(params.data[0]));
                                val += res.xName.substring(0,2) + ": " + babyAge + "<br/>" + res.yName.substring(0,2) + ": " + parseFloat(params.data[1]).toFixed(3) + yUnit;
                            }else{
                                if( params.componentType == "markPoint" ){
                                    babyAge = $servers.babyAgeDeal(res,parseFloat(params.data.coord[0]));
                                    val += res.xName.substring(0,2) + ": " + babyAge + "<br/>" + res.yName.substring(0,2) + ": " + parseFloat(params.data.coord[1]).toFixed(3) + yUnit;
                                }else{
                                    babyAge = $servers.babyAgeDeal(res,parseFloat(params.data.value[0]));
                                    val += res.xName.substring(0,2) + ": " + babyAge + "<br/>" + res.yName.substring(0,2) + ": " + parseFloat(params.data.value[1]).toFixed(3) + yUnit;
                                }
                            }
                        }else{
                            val += params.seriesName + ":" + "&nbsp;&nbsp;" + parseFloat(params.data[1]).toFixed(3) + yUnit;
                        }
                    }
                    return val;
                }
            },
            grid: {
                left: '5%',
                right: '10%',
                bottom: '8%',
                top:'10%',
                containLabel: true
            },
            xAxis: {
                type: 'value',
                name:res.xName,
                nameLocation:"middle",
                nameGap:"27",
                scale:true,
                boundaryGap: false,
                splitLine:{lineStyle:{color:"#eee"}}, //分隔线颜色
                splitArea:{ show :false },
                min:res.xMin,
                max:res.xMax,
                interval:interval,
                axisLine: {
                    lineStyle: {
                        color: "#8e7f8a"
                    }
                },
                axisLabel: {
                    textStyle: {
                        color: "#fff"
                    },
                    formatter: function(value,index){
                        if(res.timeUnit!="年"){
                            if(dom!="h-wRatio"){
                                return  value%2==0 ? value :"";
                            }else{
                                return value;
                            }
                        }else{
                            return value;
                        }
                    }
                },
                axisTick: {
                    show: false,
                    inside: true
                }
            },
            yAxis:{
                type: 'value',
                min:res.yMin,
                max:res.yMax,
                interval:res.interval,
                name:res.yName,
                nameLocation:"middle",
                nameGap:"24",
                splitLine:{lineStyle:{color:"#eee"}}, //分隔线颜色
                splitArea : {
                    show :true,//保留网格区域
                    areaStyle:{
                        color:"#fff"
                    }
                },
                axisLine: {
                    lineStyle: {
                        color: "#8e7f8a"
                    }
                },
                axisLabel: {
                    textStyle: {
                        color: "#fff"
                    }
                },
                axisTick: {
                    show: false
                }
            },
            series: [
                {
                    name: res.sd3.name,
                    type: 'line',
                    smooth:"true",
                    symbol:'circle',
                    hoverAnimation:false,
                    data: res.sd3.sd3,
                    itemStyle: {
                        normal: {
                            color: "transparent",
                            lineStyle: {
                                color: colors[res.sd3.num],
                                width:0.5
                            }
                        }
                    }
                },
                {
                    name: res.sd2.name,
                    type: 'line',
                    smooth:"true",
                    symbol:'circle',
                    hoverAnimation:false,
                    data: res.sd2.sd2,
                    itemStyle: {
                        normal: {
                            color: "transparent",
                            lineStyle: {
                                color: colors[res.sd2.num],
                                width:0.5
                            }
                        }
                    }
                },
                {
                    name: res.sd1.name,
                    type: 'line',
                    smooth:"true",
                    symbol:'circle',
                    hoverAnimation:false,
                    data: res.sd1.sd1,
                    itemStyle: {
                        normal: {
                            color: "transparent",
                            lineStyle: {
                                color: colors[res.sd1.num],
                                width:0.5
                            }
                        }
                    }
                },
                {
                    name: res.sd0.name,
                    type: 'line',
                    smooth:"true",
                    symbol:'circle',
                    hoverAnimation:false,
                    data: res.sd0.sd0,
                    itemStyle: {
                        normal: {
                            color: "transparent",
                            lineStyle: {
                                color: colors[res.sd0.num],
                                width:0.5
                            }
                        }
                    }
                },
                {
                    name: res.sd1neg.name,
                    type: 'line',
                    smooth:"true",
                    symbol:'circle',
                    hoverAnimation:false,
                    data:res.sd1neg.sd1neg,
                    itemStyle: {
                        normal: {
                            color: "transparent",
                            lineStyle: {
                                color: colors[ res.sd1neg.num],
                                width:0.5
                            }
                        }
                    }
                },
                {
                    name:  res.sd2neg.name,
                    type: 'line',
                    smooth:"true",
                    symbol:'circle',
                    hoverAnimation:false,
                    data: res.sd2neg.sd2neg,
                    itemStyle: {
                        normal: {
                            color: "transparent",
                            lineStyle: {
                                color: colors[res.sd2neg.num],
                                width:0.5
                            }
                        }
                    }
                },
                {
                    name:  res.sd3neg.name,
                    type: 'line',
                    smooth:"true",
                    symbol:'circle',
                    hoverAnimation:false,
                    data: res.sd3neg.sd3neg,
                    itemStyle: {
                        normal: {
                            color: "transparent",
                            lineStyle: {
                                color: colors[res.sd3neg.num],
                                width:0.5
                            }
                        }
                    }
                },
                {
                    name: 'baby',
                    type: 'line',
                    data:res.grownRecord,
                    symbol:'circle',
                    symbolSize:'6',
                    markPoint: {
                        itemStyle: {
                            normal: {
                                color:res.grownNowRecord[2]
                            }
                        },
                        data: [
                            {
                                xAxis: res.grownNowRecord[0],
                                yAxis: res.grownNowRecord[1]
                            }
                        ]
                    },
                    itemStyle: {
                        normal: {
                            color: sexColor,
                            lineStyle: {
                                width:3
                            }
                        },
                        emphasis:{
                            color:sexColor
                        }
                    }
                }
            ],
            animation:false
        };
        myChart.setOption(option);
        $("#" + dom + "Print").html('<img src="' + myChart.getDataURL({type:"png",backgroundColor:'#aaa'}) + '" style="width: 100%;height:100%;"/>');
    }

	/**
	 * 统一处理图表数据
	 */
	var handleDateByType = function(obj,scoreType,gender,type,type1,xType,yName,x,y,xName){
		var sexColor = gender == "F" ? "#e47db2":"#0596d5";
        var standard = obj.curvedata;
        standard.type = type;
        standard.sex = gender;
        standard.scoreType = scoreType;
        var res = $servers.dataDo2(standard);
        if( yName == "" ){
        	if( res.timeUnit == "年" ){
	            yName="身高(cm)";
	            $(".heightName").html("身高");
	        }else{
	            yName="身长(cm)";
	            $(".heightName").html("身长");
	        }
        }
        res.yName = yName;
        res.xType = xType;
        if(xName) res.xName = xName;
        trend(type1,res,x,y,sexColor);
	}

	//曲线列表：00001:体重，00002:身长，00003:头围，00004:身长别体重 00005:(BMI)年龄别体重指数
	var trends = function(data){
        var gender = data.userInfo.gender;
        var scoreType = data.scoreType;
        if( data.curveType == "01" ){
        	for (var i = 0; i < data.curvadataList.length; i++) {
        		switch( data.curvadataList[i].type ){
        			case "00001":
        				handleDateByType(data.curvadataList[i],scoreType,gender,"weight","weight","age","体重(kg)",1,1);
        				break;
        			case "00002":
        				handleDateByType(data.curvadataList[i],scoreType,gender,"height","height","age","",1,2);
        				break;
        			case "00003":
        				handleDateByType(data.curvadataList[i],scoreType,gender,"head","head","age","头围(cm)",1,3);
        				break;
        			case "00004":
        				//0-2岁，身长别体重
        				$(".length-weight-age").html("身长别体重发育曲线");
        				handleDateByType(data.curvadataList[i],scoreType,gender,"wl","h-wRatio","height","体重(kg)",5,4,"身长(cm)");
        				break;
        			case "00005":
        				//2-5岁，BMI，年龄别体重
                		$(".length-weight-age").html("BMI曲线");
        				handleDateByType(data.curvadataList[i],scoreType,gender,"wl","h-wRatio","age","BMI(kg/㎡)",1,4);
        				break;
        		}
        	}
        }else{
            if(data.curvadataList[0].timeUnit=="年"){
                $(".heightName").html("身高");
            }else{
                $(".heightName").html("身长");
            }
            var sexColor = gender == "F" ? "red":"blue";
            var series=$servers.fentonDeal(data,sexColor,gender);
            fentonTrends("feton",series,gender);
        }
    }

    /**
     * 修改指导建议
     */
    var onModify = function(){
        var params = $(this).data("params");
        var name = $(this).data("name");
        if( $(this).attr("type")=="modify" ){
            $(this).parent().next().attr("contentEditable",true).addClass("edit");
            if( $(this).parent().next().html() == "暂无" + name ) $(this).parent().next().html("");
            $(this).attr("type","save").html('<i class="fa fa-check-square" aria-hidden="true"></i>确认修改');
        }else if($(this).attr("type")=="save"){
            $(this).parent().next().removeAttr("contentEditable").removeClass("edit");
            $(this).attr("type","modify").html('<i class="fa fa-pencil-square-o" aria-hidden="true"></i>修改'+name);
            var remark = $.trim($("#remark").html());
            var guide = $.trim($("#guide").html());
            if( !remark ) $("#remark").html("暂无备注");
            if( !guide ) $("#guide").html("暂无指导建议");
            $.extend(params,{"guide":guide,"remark":remark});
            $servers.ajaxModifyGuides(params,function(){
                var guideDetails = $(this).data("guideDetails");
                $servers.ajaxGuide(params,ajaxGuideCallBack,guideDetails);
            });
        }
    }

    /**
     * 请求指导建议成功后的回调函数
     */
    var ajaxGuideCallBack = function(data,params,datas){
        var guideDetails = datas.guideDetails;
        var time = $("#growingHistory li.checkB").length > 0 ? $("#growingHistory li.checkB").html() : $("#growingHistory li.checkG").html();
        if( data ){
            $("#remark").html(data.remark);
            $("#guide,#guide-print").html(data.guide);
            $("#guiderDoctor-print").html(data.doctorName);
            $("#guiderTime-print").html(data.createTime);
        }else if( guideDetails && guideDetails.length > 0 ){
            var str = "";
            for (var i = 0; i < guideDetails.length; i++) {
                str += guideDetails[i].note + "<br/>";
            }
            $("#guide,#guide-print").html(str);
            $("#guiderDoctor-print").html(datas.doctorName);
            $("#guiderTime-print").html(time);
        }else{
            $("#guiderDoctor-print").html(datas.doctorName);
            $("#guiderTime-print").html(time);
        }
        $("#modifyGuides").unbind("click");
        $("#modifyGuides").data({"params":params,"guideDetails":guideDetails,"name":"指导建议"});
        $("#modifyGuides").click(onModify);
        $("#modifyRemark").unbind("click");
        $("#modifyRemark").data({"params":params,"guideDetails":guideDetails,"name":"备注"});
        $("#modifyRemark").click(onModify);
    }

    /**
     * 打印报告
     */
    var onPrintReport = function(){
        var params = $(this).data("params");
        var $pc = $(params.dom);
        $pc.jqprint({
            debug: false, //如果是true则可以显示iframe查看效果（iframe默认高和宽都很小，可以再源码中调大），默认是false
            importCSS: true, //true表示引进原来的页面的css，默认是true。（如果是true，先会找$("link[media=print]")，若没有会去找$("link")中的css文件）
            printContainer: true, //表示如果原来选择的对象必须被纳入打印（注意：设置为false可能会打破你的CSS规则）。
            operaSupport: true//表示如果插件也必须支持歌opera浏览器，在这种情况下，它提供了建立一个临时的打印选项卡。默认是true
        });
        return;
    };

	/**
	 * 结果数据的展示
	 */
	var resultCallBack = function(data,params){
		var handleData = $servers.handleResult(data,params);
		$ui.result({
			"id":"growthDetailResult",
			"data":handleData
		});
        $ui.result({
            "id":"growthDetailResult-print",
            "data":handleData
        });
		$ui.trends({
			"id":"growthDetailTrends",
			"data":handleData
		});
        $ui.trendsPrint({
            "id":"growthDetailTrends-print",
            "data":handleData
        });
		trends(handleData);
        $servers.ajaxGuide(params,ajaxGuideCallBack,data);
        // 打印报告
        var topbars = [
            {
                "icon":"fa fa-print",
                "name":"打印报告",
                "callback":onPrintReport,
                "params":{"dom":"#printContent"}
            }
        ];
        $bb.toolbar(topbars);
	}

	/**
	 * 选择实际年龄/纠正年龄、百分位期限图/z评分曲线图
	 */
	var onSelect = function(){
		var params = $(this).data("params");
		$(this).addClass("active").siblings().removeClass('active');
        var $li = $("#tabToggle > ul > li");
        if( $li.length == 1 ){
        	var scoreType = $li.find("div.active").attr("scoreType");
        	$.extend(params,{"scoreType":scoreType,"ageType":"02"});
        }else{
        	var scoreType = $li.eq(1).find("div.active").attr("scoreType");
        	var ageType = $li.eq(0).find("div.active").attr("ageType");
        	$.extend(params,{"scoreType":scoreType,"ageType":ageType});
        }
        $servers.ajaxGrowthData(params,resultCallBack);
	}

	/**
	 * 查询患者生长发育记录信息,情趣成功后的回调函数
	 */
	var ajaxGrowthDataCallBack = function(data,params){
		$ui.info({
			"id":"growthDetailInfo",
			"data":data.userInfo
		});
        $ui.info({
            "id":"growthDetailInfo-print",
            "data":data.userInfo
        });
		$ui.tab({
			"id":"tabToggle",
			"data":data.userInfo
		});
		$("#tabToggle div").unbind("click");
		$("#tabToggle div").data("params",params);
		$("#tabToggle div").click(onSelect);
		resultCallBack(data,params);
	}

	/**
	 * 选择某一个记录
	 */
	event.onRecordSelect = function(){
        var params = $(this).data("params");
		var recordId = $(this).attr("recordId");
		var gender = $(this).attr("gender");
		if( gender == "F" ){
          	$(this).addClass("checkG").siblings().removeClass("checkG");
      	}else{
          	$(this).addClass("checkB").siblings().removeClass("checkB");
      	}
        /**
         * ageType: 
         *     "01":纠正年龄
         *     "02":实际年龄
         * scoreType:
         *     "01":百分位曲线
         *     "02":z评分曲线     
         */
        $.extend(params,{"recordId":recordId,"ageType":"01","scoreType":"01"});
      	$servers.ajaxGrowthData(params,ajaxGrowthDataCallBack);
	}

	return event;
});